import os
import tkinter as tk
from tkinter import filedialog, messagebox

def split_bin_file(input_path, chunk_size_kb, output_dir):
    chunk_size = chunk_size_kb * 1024  # 转换为字节
    file_index = 1
    
    try:
        with open(input_path, 'rb') as f:
            while True:
                chunk = f.read(chunk_size)
                if not chunk:
                    break
                # 生成分块文件名（保留原文件名+序号）
                base_name = os.path.basename(input_path)
                output_path = os.path.join(output_dir, f"{base_name}_part{file_index}.bin")
                with open(output_path, 'wb') as chunk_file:
                    chunk_file.write(chunk)
                file_index += 1
        return True
    except Exception as e:
        messagebox.showerror("错误", f"分割失败: {str(e)}")
        return False

class BinSplitterGUI:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Bin文件分割工具")
        
        # 文件选择组件
        self.file_path = tk.StringVar()
        tk.Label(self.window, text="目标文件:").grid(row=0, column=0, padx=5, pady=5)
        tk.Entry(self.window, textvariable=self.file_path, width=40).grid(row=0, column=1)
        tk.Button(self.window, text="浏览", command=self.choose_file).grid(row=0, column=2)
        
        # 分割大小输入
        tk.Label(self.window, text="分块大小 (kB):").grid(row=1, column=0, padx=5, pady=5)
        self.chunk_size = tk.IntVar(value=10)
        tk.Entry(self.window, textvariable=self.chunk_size).grid(row=1, column=1)
        
        # 开始按钮
        tk.Button(self.window, text="开始分割", command=self.start_split).grid(row=2, column=1, pady=10)
        
    def choose_file(self):
        path = filedialog.askopenfilename(filetypes=[("BIN文件", "*.bin")])  # 文件选择功能[6,8](@ref)
        if path:
            self.file_path.set(path)
    
    def start_split(self):
        input_path = self.file_path.get()
        chunk_size = self.chunk_size.get()
        output_dir = os.path.dirname(input_path)
        
        if not input_path:
            messagebox.showwarning("警告", "请先选择文件")
            return
        if chunk_size <= 0:
            messagebox.showwarning("警告", "分块大小必须大于0")
            return
        
        if split_bin_file(input_path, chunk_size, output_dir):
            messagebox.showinfo("完成", "文件分割成功！")

if __name__ == "__main__":
    app = BinSplitterGUI()
    app.window.mainloop()
